<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2018/6/21
 * Time: 16:50
 */

namespace app\common\cachemodel;

use app\common\cachemodel\zl4\Zl4GoodTimeTag;
use app\common\cachemodel\zl4\Zl4HoroscopeGoodTimeTemp;
use app\common\cachemodel\zlcr2\Zlcr2UserQuestion;
use app\common\lib\exception\ApiException;
use app\common\lib\Util;
use app\common\model\BaseCache;
use app\common\model\Recode;
use think\Env;
use think\Log;
use XznsTools\cache\CacheManage;

/**
 * 商品相关模型
 * Class Goods
 * @package app\common\model
 */
class Goods extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.app_goods';
    protected $cacheModel = 'goods.goods';


    /**
     * 获取指定商品类型图
     * @param $type
     * @return string
     */
    public static function goodsImg($type)
    {
        switch ($type)
        {
            case 29:
                return Env::get('host.photo') . '/test/order/meditation.png';
            case 30://AI解答(骰子塔罗)
            case 31:
                return Env::get('host.photo') . '/test/order/ai_answer.png';
            case 32://后天星座
                return Env::get('host.photo') . '/test/order/acquired_astro.png';
            case 34://AI疗愈
                return Env::get('host.photo') . '/test/order/ai_voice.png';
            case 35:
                return Env::get('host.photo').'/test/order/name_analyze.png';
            default :
                return '';
        }
    }

    /**
     * 获取app版本苹果审核信息
     * @throws \Exception
     */
    public function getAppAppleInfo()
    {
        $arr = [];
        $header = request()->header();
        $header['app-type'] = $header['app-type'] ?? '';
        $header['version'] = $header['version'] ?? '';
        $arr['apple_goods'] = config('apple_pay_goods');
        $arr['is_apple_pay'] = false;
        $arr['android_audit_mode_swtich'] = false;
        $arr['header'] = $header;
        $arr['is_apple_check'] = false;
        $arr['apple_pay_sandbox_model'] = false;

        if (isset($header['app-type'], $header['version']) && $header['version'])
        {
            //获取app当前版本信息
            $AppVersion = (new AppVersion())->getVersionInfo($header['app-type'], $header['version'], [
                'is_apple_pay',
                'version_name',
                'apple_goods',
                'android_audit_mode_swtich',
                'extend'
            ]);
            if (isset($AppVersion['extend']) && $AppVersion['extend'])
            {
                $extend = json_decode($AppVersion['extend'], true);
            } else
            {
                $extend = [];
            }
            $AppVersion['apple_pay_sandbox_model'] = $extend['ios']['apple_pay_sandbox_model'] ?? false;
            $AppVersion['version_name'] = $AppVersion['version_name'] ?? 'V' . $header['version'];
            // 判断当前版本是否开启审核
            if ('V' . $header['version'] === $AppVersion['version_name'])
            {
                if ($header['app-type'] === 'ios')
                {
                    $AppVersion['is_apple_pay'] = $AppVersion['is_apple_pay'] ?? 0;
                    $AppVersion['apple_goods'] = $AppVersion['apple_goods'] ?? [];
                    // 控制苹果商品显示
                    if ($AppVersion['apple_goods'])
                    {
                        $arr['is_apple_pay'] = true;
                    }
                    // 控制苹果审核模式
                    if ($AppVersion['is_apple_pay'])
                    {
                        $arr['is_apple_check'] = true;
                    }
                    // 控制苹果沙箱
                    if ($AppVersion['apple_pay_sandbox_model'])
                    {
                        $arr['apple_pay_sandbox_model'] = true;
                    }
                } elseif ($header['app-type'] === 'android')
                {
                    $AppVersion['android_audit_mode_swtich'] = $AppVersion['android_audit_mode_swtich'] ?? 0;
                    // 控制安卓审核模式
                    if ($AppVersion['android_audit_mode_swtich'])
                    {
                        $arr['android_audit_mode_swtich'] = true;
                    }
                }
            }
        }

        return $arr;
    }

    /**
     * @param      $type 0=>全部 1=>校准生辰 2=>日运 3=>月运 4=>年运 5=>幸运之城 6=>教学视频 7=>本命预测 8=>vip 9=>准币
     * @param bool $is_apple_pay
     * @param bool $apple_check
     * @return array|mixed
     * @throws \Exception
     */
    public function GoodsTypeInfo($type)
    {
        $ids = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $type)->ZsGetIocData('list', function () use ($type)
        {
            return $this->getGoodsTypeInfoFromDms($type);
        });
        if ($type === 8 && !(Util::IsIos() && Util::CheckAppVersion('2.9.7') === '大'))
        {
            $tmpIds = [];
            foreach ($ids as $id)
            {
                if ($id < 20100)
                {
                    $tmpIds[] = $id;
                }
            }
            $ids = $tmpIds;
        }
        $data = [];
        if ($ids)
        {
            $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel)->batchGetCache($ids, function ($ids) use ($type)
            {
                return $this->getInfoByIdsInData($ids, $type, 'DESC');
            }, [], 'list_details');
            // 使用 usort 进行排序
            usort($data, function ($a, $b)
            {
                if ($a['sort'] !== $b['sort'])
                {
                    return $a['sort'] <=> $b['sort'];
                }
                return $a['id'] <=> $b['id'];
            });

        }

        //本命报告活动信息
        //        if ($type === 7)
        //        {
        //            $activingModel = new ZhunleActivity();
        //            // 获取活动商品信息
        //            foreach ($data as $key => $v)
        //            {
        //                $data[$key]['active_time'] = 0; // 活动时间默认值
        //                $activing = $activingModel->getActivingGood(7, $v['id']);
        //                if ($activing)
        //                {
        //                    $v['active_time'] = $activing['end_time'] - time(); // 活动时间默认值
        //                    switch ($activing['type'])
        //                    {
        //                        case 1: // 打折
        //                            $v['now_prize'] = sprintf('%.2f', $v['now_prize'] * $activing['attr']);
        //                            break;
        //                        case 2: // 固定价
        //                            $v['now_prize'] = sprintf('%.2f', $activing['attr']);
        //                            break;
        //                        case 3:// 买一送一价格不变
        //                        default:// 未知价格不变
        //                    }
        //                    // 替换活动信息
        //                    $data[$key] = array_merge($v, array_filter($activing['extend'] ?: []));
        //                }
        //            }
        //        }

        $header = $this->getAppAppleInfo();
        //若是app请求则判断是否ios还是安卓且是否为准币商品
        if (in_array($header['header']['app-type'], ['ios', 'android']) && $type == 9)
        {
            //判断当前是否是苹果支付
            if ($header['is_apple_pay'] || $header['is_apple_check'])
            {
                $appleGoods = $this->getAppleGoods($type, $data, $header['apple_goods']);
                if ($appleGoods)
                {
                    $data = $appleGoods;
                }
            }
        }

        if ($data)
        {
            switch ($type)
            {
                case 17:// 合盘报告
                    $synastryReportConfig = config('synastryreport');
                    $resData = [];
                    $goodInfoRes = [];
                    foreach ($data as $goodItem)
                    {
                        $goodInfoRes[$goodItem['id']] = $goodItem;
                    }
                    foreach ($synastryReportConfig as $key => $item)
                    {
                        $resData[$key] = [
                            'srid' => $key,
                            'gids' => array_keys($goodInfoRes),
                            'good_type' => $item['good_type'],
                            'relation_list' => $item['relation_list'],
                            'relation_img' => $item['relation_img'],
                            'header_bg' => $item['header_bg'],
                            'header_bg_x' => $item['header_bg_x'],
                            'score' => NULL,
                            'text' => NULL,
                            'alert_bg_img1' => NULL,
                            'alert_bg_img2' => NULL,
                            'bg_img' => $item['bg_img'],
                            'small_bg_img' => $item['small_bg_img'],
                            'large_active_bg_img' => $item['large_active_bg_img'],
                            'small_active_bg_img' => $item['small_active_bg_img'],
                            'title_img' => NULL,
                            'base_num' => $item['base_num'],
                            'intro' => NULL,
                            'color' => $item['color'],
                            'is_large' => $item['is_large'],
                            'status' => $item['status'],
                            'type' => 17,
                            'name' => $item['good_name'],
                            'default_data' => $item['default_data']
                        ];

                        foreach ($item['good_list'] as $gid => $gData)
                        {
                            $item['good_list'][$gid] = array_merge($gData, $goodInfoRes[$gid]);
                        }

                        $resData[$key]['good_list'] = $item['good_list'];

                        if (!isset($item['default_data']['price']) || !$item['default_data']['price'])
                        {
                            $resData[$key]['default_data']['price'] = $item['good_list'][current(current($item['relation_list'])['gids'])]['now_prize'];
                        }
                    }

                    $data = $resData;
                    break;
                case 22:  // 问答
                    $question = config('zlcr2_question')['info'];
                    $resData = [];
                    $data = array_column($data, null, 'id');
                    foreach ($data as $key => $datum)
                    {
                        $datum['id'] = (int)$datum['id'];
                        $datum['sort'] = (int)$datum['sort'];
                        $datum['status'] = (int)$datum['status'];
                        if (isset($question[$key]))
                        {
                            $datum['is_add'] = 0;
                            $tmp = array_merge($datum, $question[$key]);
                        } else //追问
                        {
                            $datum['is_add'] = 1;
                            $tmp = $datum;
                        }
                        $resData[$key] = $tmp;
                    }
                    $data = $resData;
                    break;
            }
        }
        return $data;
    }

    /**
     * 不同版本vip商品
     * @param int $uid
     * @return array
     * @throws \Exception
     */
    public function getVipGoodsVersion(int $uid = 0)
    {
        $goods = $this->GoodsTypeInfo(8);
        $res = [];
        foreach ($goods as $item)
        {
            $item['id'] = (int)$item['id'];
            if (Util::CheckAppVersion('2.10.5') !== '小')
            {
                if (Util::IsIos())
                {
                    $tmpGid = [20107, 20108, 20109, 20110, 20112, 20111];
                    //已订阅不展示订阅商品
                    $UserVip = (new ZlUserVip())->getUserVipFromCache($uid);
                    if ($UserVip && (int)$UserVip['apple_status'] === 1 && in_array($item['id'], [20112, 20111], true))
                    {
                        $tmpGid = [20107, 20108, 20109, 20110];
                    }
                } else
                {
                    $tmpGid = [154, 155, 156, 157];
                }
            } elseif (Util::CheckAppVersion('2.9.10') !== '小')
            {
                if (Util::IsIos())
                {
                    $tmpGid = [20100, 20101, 20102, 20103, 20106, 20105];
                    //已订阅不展示订阅商品
                    $UserVip = (new ZlUserVip())->getUserVipFromCache($uid);
                    if ($UserVip && (int)$UserVip['apple_status'] === 1 && in_array($item['id'], [20106, 20105], true))
                    {
                        $tmpGid = [20100, 20101, 20102, 20103];
                    }
                } else
                {
                    $tmpGid = [35, 36, 37, 38];
                }
            } elseif (Util::CheckAppVersion('2.9.8') !== '小')
            {
                if (Util::IsIos())
                {
                    $tmpGid = [20100, 20101, 20102, 20103];
                } else
                {
                    $tmpGid = [35, 36, 37, 38];
                }
            } else
            {
                $tmpGid = [35, 36, 37, 38];
            }
            if (in_array((int)$item['id'], $tmpGid, true))
            {
                $res[] = $item;
            }
        }

        // 对数组进行排序
        usort($res, static function ($a, $b)
        {
            if ($a['sort'] === $b['sort'])
            {
                return 0;
            }
            return ($a['sort'] > $b['sort']) ? -1 : 1;
        });
        return $res;
    }

    /**
     * 数据库获取商品信息
     * @param $type 1=>校准生辰 2=>日运 3=>月运 4=>年运 5=>幸运之城 6=>教学视频 7=>本命预测 8=>会员 ，9=>准币，12=>月运精简版，13=>本命报告精简版
     * @return array
     */
    public function getGoodsTypeInfoFromDms($type)
    {
        if ($type)
        {
            $where = ['type' => $type, 'status' => ['neq', 0]];
        } else
        {
            $where = ['status' => ['neq', 0]];
        }
        try
        {
            $ids = $this->where($where)->order('sort', 'DESC')->column('id', 'id');
            if ($type === 8)
            {
                $tmpIds = array_keys(config('apple_pay_goods.ios_vip_goods'));
                $ids = array_merge($ids, $tmpIds);
            }
            $ids = array_flip_key_value($ids);
        }
        catch (\Exception $e)
        {
            $ids = [];
        }

        return $ids;
    }

    /**
     * 从数据库批量获取商品信息
     * @param $ids
     * @param $type
     * @param $sortType
     * @return array|false|mixed|string|null
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        $ids = is_array($ids) ? $ids : explode(',', $ids);

        //判断id是否包含本命预测
        $result = array_intersect($ids, [39, 40, 41, 42, 52, 54, 55, 56, 57, 58,]); // 39, 40, 41, 42, 52=>完整版本命报告商品ID 54, 55, 56, 57, 58=>精简版本命报告
        $orderType = 0;
        if (count($result) >= 1)
        {
            $orderType = 7; // 本命报告
        }
        if (count(array_intersect($ids, config('goods.vip_id'))) >= 1)
        {
            $orderType = 8;
        }

        try
        {
            switch ($orderType)
            {
                case 7: // 本命报告  精简版查询语句和完整版相同
                    $order = $this->alias('g')->join('wechat_backup_07_18_14_43_00.zl_natal_goods n', 'g.id=n.gid')->where('g.id', 'in', $ids)->column('g.id,g.sort,g.status,g.type,g.name,g.or_prize,g.now_prize,g.expire_time,g.extend,n.flag,n.intro,n.color,n.alert_bg_img1,n.alert_bg_img2,n.bg_img,n.title_img,n.header_bg,n.content_bg,n.base_num,n.text_num,n.is_new,n.is_recommend_index,n.mini_desc', 'g.id');//,n.is_new,n.is_recommend_index
                    break;
                case 8:
                    $configGoods = config('apple_pay_goods.ios_vip_goods');
                    $configGidsTmp = [];
                    $gids = [];
                    foreach ($ids as $id)
                    {
                        if ($id >= 20100)
                        {
                            $configGidsTmp[$id] = $configGoods[$id];
                        } else
                        {
                            $gids[] = $id;
                        }
                    }
                    $goods = $this->where('id', 'in', $gids)->column('id,sort,status,type,name,or_prize,now_prize,expire_time,extend', 'id');
                    $order = $goods + $configGidsTmp;
                    break;
                default:
                    $order = $this->where('id', 'in', $ids)->column('id,sort,status,type,name,or_prize,now_prize,expire_time,extend', 'id');
            }
        }
        catch (\Exception $e)
        {
            Log::write('getInfoByIdsInData:' . $e->getMessage(), 'error');
            $order = NULL;
        }

        return $order;
    }


    /**
     * 缓存批量获取数据
     * @param $cids
     * @param $field
     * @return array
     * @throws \Exception
     */
    public function batchGetInfoByIds($cids, $field = [])
    {
        $data = parent::batchGetInfoByIds($cids, $field);
        foreach ($data as $key => $datum)
        {
            $this->restGoodsExpireTime($datum);
            $data[$key] = $datum;
        }
        return $data;
    }

    /**
     * 重置商品过期时间
     * @param $goods
     * @return void
     * @throws \Exception
     */
    public function restGoodsExpireTime(&$goods)
    {
        $goods['id'] = (int)$goods['id'];
        if (!in_array($goods['id'], [20106, 20105], true))
        {
            return;
        }
        try
        {
            $isSandboxModel = $GLOBALS['appleNotifySandboxModel'];
        }
        catch (\Exception $e)
        {
            $header = request()->header();
            if (isset($header['app-type'], $header['version']))
            {
                //获取app当前版本信息
                $AppVersion = (new AppVersion())->getVersionInfo($header['app-type'], $header['version'], ['is_apple_pay', 'extend']);
                if (isset($AppVersion['extend']) && $AppVersion['extend'])
                {
                    $extend = json_decode($AppVersion['extend'], true);
                } else
                {
                    $extend = [];
                }
                $isSandboxModel = $extend['ios']['apple_pay_sandbox_model'] ?? false;
            } else
            {
                $isSandboxModel = false;
            }
        }
        if ($isSandboxModel)
        {
            $subs = (new AppConfig())->configInfo('subs');
            if ($goods['id'] === 20106)
            {
                $goods['expire_time'] = $subs['sandbox_apple_month'];
            } elseif ($goods['id'] === 20105)
            {
                $goods['expire_time'] = $subs['sandbox_apple_year'];
            }
        }
    }

    /**
     * 获取苹果商品信息
     * @param       $type
     * @param array $goods 准了商品
     * @param array $apple_goods_arr 苹果商品
     * @return array
     */
    public function getAppleGoods($type, $goods, $apple_goods_arr)
    {
        switch ($type)
        {
            //            // 苹果审核时不能有会员商品，此处不处理
            //            case 1:
            //                $apple_goods = $apple_goods_arr['rec_goods'];
            //                break;
            //            case 2:
            //                $apple_goods = $apple_goods_arr['fortune_day_goods'];
            //                break;
            //            case 3:
            //                $apple_goods = $apple_goods_arr['fortune_month_goods'];
            //                break;
            //            case 4:
            //                $apple_goods = $apple_goods_arr['fortune_year_goods'];
            //                break;
            //            case  5:
            //                $apple_goods = $apple_goods_arr['acg_goods'];
            //                break;
            //            case 6:
            //                $apple_goods = $apple_goods_arr['video_goods'];
            //                break;
            //            case 7:
            //                $apple_goods = $apple_goods_arr['natal_report_goods'];
            //                break;
            //            case 8:
            //                $apple_goods = $apple_goods_arr['vip_goods'];
            case 9:
                $apple_goods = $apple_goods_arr['coin_goods'];
                break;
            default:
                return [];
        }
        foreach ($goods as $k => $good)
        {
            foreach ($apple_goods as $apple_good)
            {
                //将商品价格进行调整为苹果价格，苹果名称
                if ($good['id'] == $apple_good['gid'])
                {
                    $goods[$k]['gid'] = $good['id'];
                    $goods[$k]['price'] = $apple_good['price'];
                    $goods[$k]['now_prize'] = $apple_good['price'];
                    $goods[$k]['active_time'] = 0;
                    continue;
                }
            }
        }

        return $goods;
    }

    /**
     * @param int $type 运输类型 2=>日运，3=>月运，4=>年运
     * @param int $uid 用户id
     * @param int $rid 档案id
     * @param int $gid 商品id
     * @param string $start_time 运势开始时间
     * @return string|null
     * @throws \app\common\lib\exception\ApiException
     */
    public function getFortuneUnlockInfo($type, $uid, $rid, $gid = 0, $start_time = '')
    {
        if (!in_array($type, [2, 3, 4]) || !$rid || !$gid)
        {
            return '';
        }
        //检测运势时间格式
        $time = Util::FormatFortuneTime($type, $start_time, $gid);
        switch ($type)
        {
            case 2:
                $start_time = dateModify('Y-m-d', $time['start_time']);
                $end_time = dateModify('Y-m-d', $time['end_time']);
                break;
            case 3:
                $start_time = dateModify('Y-m', $time['start_time']);
                $end_time = dateModify('Y-m', $time['end_time']);
                break;
            case 4:
                $start_time = dateModify('Y', $time['start_time']);
                $end_time = dateModify('Y', $time['end_time']);
                break;
        }
        //获取解锁的时间范围
        $timeRange = prDates(['start' => $start_time, 'end' => $end_time, 'type' => $type - 1]);
        //将解锁的时间范围改为时间戳
        $fortuneTimeRange = array_map(function ($timeValue)
        {
            return strtotimeModify('U', $timeValue);
        }, $timeRange);
        //获取运势购买信息
        $fortuneInfo = FortuneCache::getUnlockFortune($uid, $rid, $type);
        $unlockNum = 0;
        $fortuneUnlcokTime = [];
        //获取已经购买的时间范围和数量
        foreach ($fortuneTimeRange as $item)
        {
            if (in_array($item, $fortuneInfo['unlock_fortune']))
            {
                $fortuneUnlcokTime[] = $item;
                $unlockNum++;
            }
        }

        $notice = NULL;
        //获取商品名称
        if ($unlockNum)
        {
            switch ($gid)
            {
                case 3:
                    $fortuneName = '月度';
                    break;
                case 4:
                    $fortuneName = '季度';
                    break;
                case 5:
                    $fortuneName = '半年';
                    break;
                case 6:
                    $fortuneName = '年度';
                    break;
                case 21:
                    $fortuneName = '三个月';
                    break;
                case 22:
                    $fortuneName = '六个月';
                    break;
                case 23 :
                    $fortuneName = '十二个月';
                    break;
                case 25:
                    $fortuneName = '三年';
                    break;
                case 26:
                    $fortuneName = '五年';
                    break;
                case 27:
                    $fortuneName = '十年';
                    break;
                default :
                    $fortuneName = '';
                    break;
            }
            $fortuneUnlcokTime = current($fortuneUnlcokTime) ?: time();
            switch ($type)
            {
                case 2:
                    if ($fortuneInfo['unlock_fortune'])
                    {
                        if ($unlockNum === 1)
                        {
                            $notice = '您已购买的' . $fortuneName . '日运中' . dateModify('n月j日', $fortuneUnlcokTime) . '已解锁，继续购买将覆盖，请知晓';
                        } else
                        {
                            $notice = '您已购买的' . $fortuneName . '日运中' . dateModify('n月j日', $fortuneUnlcokTime) . '等' . $unlockNum . '日已解锁，继续购买将覆盖，请知晓';
                        }
                    }
                    break;
                case 3:
                    if ($fortuneInfo['unlock_fortune'])
                    {
                        if ($unlockNum === 1)
                        {
                            $notice = '您已购买的' . $fortuneName . '运势中' . dateModify('n月', $fortuneUnlcokTime) . '已解锁，继续购买将覆盖，请知晓';
                        } else
                        {
                            $notice = '您已购买的' . $fortuneName . '运势中' . dateModify('n月', $fortuneUnlcokTime) . '等' . $unlockNum . '个月已解锁，继续购买将覆盖，请知晓';
                        }
                    }
                    break;
                case 4:
                    if ($fortuneInfo['unlock_fortune'])
                    {
                        if ($unlockNum === 1)
                        {
                            $notice = '您已购买的' . $fortuneName . '运势中' . dateModify('Y年', $fortuneUnlcokTime) . '已解锁，继续购买将覆盖，请知晓';
                        } else
                        {
                            $notice = '您已购买的' . $fortuneName . '运势中' . dateModify('Y年', $fortuneUnlcokTime) . '等' . $unlockNum . '年已解锁，继续购买将覆盖，请知晓';
                        }
                    }
                    break;
            }
        }

        return $notice;
    }

    /**
     * @param int $uid 用户ID
     * @param int $rid1
     * @param int $rid2
     * @param int $srid 合盘报告类型ID
     * @param int $relationId 关系ID
     * @param int $startDate 开始日期 202001
     * @param int $endDate 结束日期 202012
     * @return string
     */
    public function getSynastryReportUnlockNotice(int $uid, int $rid1, int $rid2, int $srid, int $relationId, int $startDate, int $endDate): ?string
    {
        $unlockMonthArray = (new ZlSynastryReportUnlockTimeInfo())->getUnlockMonthInfo($uid, $rid1, $rid2, $srid, $relationId, $startDate, $endDate);

        asort($unlockMonthArray);

        if ($unlockMonthArray)
        {
            $numMonth = count($unlockMonthArray);
            if ($numMonth > 1)
            {
                $startDateTime = date('Y年m月', strtotime($unlockMonthArray[0] . '01'));
                $endDateTime = date('Y年m月', strtotime($unlockMonthArray[$numMonth - 1] . '01'));
                return "您已经购买的两人相同类型的合盘报告中包含{$startDateTime}至{$endDateTime}时段中{$numMonth}个月，请知晓";
            } else
            {
                $startDateTime = date('Y年m月', strtotime($unlockMonthArray[0] . '01'));
                return "您已经购买的两人相同类型的合盘报告中包含{$startDateTime}，请知晓";
            }
        } else
        {
            return '';
        }
    }

    /**
     * 获取吉时吉日标签商品信息
     * @param $uid
     * @param $historyId
     * @param int $checkStatus 检测结果状态
     * @return array
     * @throws ApiException
     */
    public function getBaziJsjrGoods($uid, $historyId, int $checkStatus = 0)
    {
        $GoodTimeSimData = (new Zl4HoroscopeGoodTimeTemp())->getInfoById($historyId, ['uid', 'tid', 'unlock_day_num', 'status']);
        if (!$GoodTimeSimData || $GoodTimeSimData['uid'] != $uid)
        {
            throw new ApiException('服务异常，请稍后重试！');
        }
        if ($checkStatus)
        {
            if (in_array($GoodTimeSimData['status'], [1, 3], false))
            {
                throw new ApiException('服务异常，请稍后重试！');
            }
            if ((int)$GoodTimeSimData['status'] === 4)
            {
                throw new ApiException('当前商品已购买！');
            }
        }
        $tagInfo = (new Zl4GoodTimeTag())->getInfoById($GoodTimeSimData['tid'], ['gid', 'extend']);
        $goodsInfo = $this->getInfoById($tagInfo['gid']);
        switch (true)
        {
            case $GoodTimeSimData['unlock_day_num'] >= 90:
                $discount = isset($tagInfo['extend']['discount']['discount_90']) && $tagInfo['extend']['discount']['discount_90'] && $tagInfo['extend']['discount']['discount_90'] > 0 ? $tagInfo['extend']['discount']['discount_90'] : 1;
                break;
            case $GoodTimeSimData['unlock_day_num'] >= 60:
                $discount = isset($tagInfo['extend']['discount']['discount_60']) && $tagInfo['extend']['discount']['discount_60'] && $tagInfo['extend']['discount']['discount_60'] > 0 ? $tagInfo['extend']['discount']['discount_60'] : 1;
                break;
            case $GoodTimeSimData['unlock_day_num'] >= 30:
                $discount = isset($tagInfo['extend']['discount']['discount_30']) && $tagInfo['extend']['discount']['discount_30'] && $tagInfo['extend']['discount']['discount_30'] > 0 ? $tagInfo['extend']['discount']['discount_30'] : 1;
                break;
            default:
                $discount = 1;
        }

        return [
            'goods' => [
                [
                    'now_prize' => $goodsInfo['now_prize'] * $GoodTimeSimData['unlock_day_num'] * $discount,
                    'type' => $goodsInfo['type'],
                    'status' => $goodsInfo['status'],
                    'or_prize' => $goodsInfo['now_prize'] * $GoodTimeSimData['unlock_day_num'],
                    'expire_time' => '',
                    'sort' => $goodsInfo['sort'],
                    'name' => $goodsInfo['name'],
                    'id' => $goodsInfo['id'],
                    'extend' => $goodsInfo['extend'],
                ]
            ],
            'history' => $GoodTimeSimData
        ];
    }

    /**
     * 获取合盘商品信息
     * @return array
     * @throws \Exception
     */
    public function getSynastryReportGoods($gid)
    {
        $goods = $this->GoodsTypeInfo(17);
        $goodsRes = [];
        foreach ($goods as $k => $good)
        {
            foreach ($good['relation_list'] as $relationIdKey => $relationItem)
            {
                if (in_array($gid, $relationItem['gids'], true))
                {
                    $srid = $k;
                    $relationId = $relationIdKey;
                    break;
                }
            }
            foreach ($good['relation_list'][$relationId]['gids'] as $gidKey)
            {
                $goodItem = $good['good_list'][$gidKey];
                $goodsRes[$gidKey] = [
                    'now_prize' => $goodItem['now_prize'],
                    'type' => $goodItem['type'],
                    'status' => $goodItem['status'],
                    'or_prize' => $goodItem['or_prize'],
                    'expire_time' => $goodItem['expire_time'],
                    'sort' => $goodItem['sort'],
                    'name' => $goodItem['name_desc'],
                    'id' => $goodItem['id'],
                    'extend' => $goodItem['extend'],
                    'srid' => $srid,
                    'relation_id' => $relationId
                ];
            }
        }
        return $goodsRes;
    }


    /**
     * 判断当前商品是否是吉时吉日
     * @param $type
     * @param $gid
     * @return bool
     */
    public static function isBaziJsjr($type, $gid)
    {
        if ((int)$type === 28)
        {
            if (in_array((int)$gid, [106, 107], true))
            {
                return false;
            }
            return true;
        }
        return false;
    }

    ############################################## todo 版本2.7.0之前的逻辑 ################################################

    /**
     * 商品结构重组
     * @param $header
     * @param        $type
     * @param        $goods
     * @param int $rid
     * @param int $rid2
     * @param string $start_time
     * @param int $gid
     * @return array
     * @throws ApiException
     */
    public function resetGoodsInfo($header, $type, $goods, $rid = 0, int $rid2 = 0, $start_time = '', $gid = 0)
    {
        $type = (int)$type;
        $discount = 0;
        $arr = $arr['active_data'] = null;
        $srid = 0;
        $relationId = NULL;
        $endTime = null;
        //商品信息根据商品类型进行处理
        switch (true)
        {
            //若是校准生辰，视频获取具体商品信息
            //                case 1:
            //                    $goods = $goods ? array_shift($goods) : [];
            //                    break;
            case in_array($type, [6, 16, 17], true)://教学视频,塔罗,合盘报告 只获取一个具体的商品信息
                foreach ($goods as $k => $good)
                {
                    if ($type === 17)
                    {
                        foreach ($good['relation_list'] as $relationIdKey => $relationItem)
                        {
                            if (in_array($gid, $relationItem['gids'], true))
                            {
                                $srid = $k;
                                $relationId = $relationIdKey;
                            }
                        }
                        if (!$relationId)
                        {
                            unset($goods[$k]);
                            continue;
                        }
                    } else
                    {
                        if ($good['id'] != $gid)
                        {
                            unset($goods[$k]);
                            continue;
                        }
                    }

                    if ($type === 17)
                    {
                        $goodsData = [];
                        foreach ($good['relation_list'][$relationId]['gids'] as $gidItem)
                        {
                            $goodsData[$gidItem] = [
                                'id' => $gidItem,
                                'name' => $good['good_list'][$gidItem]['name_desc'],
                                'extend' => $good['good_list'][$gidItem]['extend'],
                                'now_prize' => $good['good_list'][$gidItem]['now_prize'],
                            ];
                        }
                        $goods = $goodsData;
                        $arr['fortune_time_range'] = [
                            'start_time' => date('Y-m'),
                            'end_time' => '2058-01',
                        ];
                        $sTime = strtotime($start_time . '-01');
                        $start_time = (int)date('Ym', $sTime);
                        $endTime = (int)date('Ym', strtotime($good['good_list'][$gid]['expire_time'], $sTime));
                    }
                }
                break;
            case in_array($type, [5, 7], true)://地图和本命预测商品处理，判断商品是否购买以及幸运之城打包价格处理
                $goods_gids = array_column($goods, 'id');
                $unlcok_goods = OrdersLib::CheckPayGids($header->user['id'], $rid, $type, $goods_gids, $rid2);
                $unlock_gids = $unlcok_goods['gids'] ?? [];
                $goods1 = [];
                $goods2 = [];//打包的商品
                foreach ($goods as $k => $value)
                {
                    $is_unlock = 0;
                    //获取用户解锁的数据
                    foreach ($unlock_gids as $item)
                    {
                        switch (true)
                        {
                            case (int)$item === 19://若为打包购买，全部显示已解锁
                            case (int)$item === (int)$value['id']://判断当前商品是否已解锁
                                $is_unlock = 1;
                                break;
                        }
                    }
                    //获取app默认解锁的数据
                    switch (true)
                    {
                        case $value['id'] == 19 || $value['status'] == 2:
                            //幸运之城打包价格
                            $arr['pack_price'] = $value['now_prize'];
                            unset($goods[$k]);
                            break;
                        case $value['id'] == 14://变革线
                        case $value['id'] == 15://梦想线
                            $is_unlock = 1;
                            break;
                    }
                    //商品排序
                    if (in_array($value['id'], [14, 15]))
                    {
                        $goods1[] = [
                            'id' => $value['id'],
                            'name' => $value['name'],
                            'extend' => $value['extend'],
                            'now_prize' => $value['now_prize'],
                            'is_unlock' => $is_unlock,
                        ];
                    } else if ($value['id'] != 19 && $value['status'] != 2)
                    {
                        $goods2[] = [
                            'id' => $value['id'],
                            'name' => $value['name'],
                            'extend' => $value['extend'],
                            'now_prize' => $value['now_prize'],
                            'is_unlock' => $is_unlock,
                        ];
                    }
                }
                //重组排序后的数据
                $array1 = array_column($goods2, 'id');
                array_multisort($array1, SORT_NUMERIC, SORT_ASC, $goods2);// 得到按 id 排序结果
                $goods = array_merge($goods1, $goods2);
                break;
            case $type === 3://获取月运购买时间范围
                $arr['fortune_time_range'] = [
                    'start_time' => config('fortune.fortune_time_range')['month']['start'],
                    'end_time' => config('fortune.fortune_time_range')['month']['end'],
                ];
                break;
            case $type === 4://获取年运购买时间范围
                $arr['fortune_time_range'] = [
                    'start_time' => date('Y'),// 不能购买之前的运势
                    'end_time' => config('fortune.fortune_time_range')['year']['end'],
                ];
                break;
            default:
                break;
        }
        $activingModel = new ZhunleActivity();
        foreach ($goods as $k => $good)
        {
            $extend = json_decode($good['extend'], true);
            if (Util::CheckAppVersion('2.9.7') === '大' && Util::IsIos())
            {
                $good_des = $extend['ios_goods_des'] ?? '';
            } else
            {
                $good_des = $extend['goods_des'] ?? '';
            }
            $goods[$k]['gid'] = (int)$good['id'];
            $goods[$k]['des'] = $good_des;
            $goods[$k]['price'] = $good['now_prize'];
            //若当前是vip，则获取vip有效时间
            if ($type === 8)
            {
                //获取用户当前vip有效时间
                $UserVip = OrdersLib::getUserVipTime($header->user['id'], $good['id']);
                $goods[$k]['vip_expired_des'] = '会员有效期至' . date('Y-m-d', $UserVip['vip_end_time']);
            }
            unset($goods[$k]['id'], $goods[$k]['sort'], $goods[$k]['status'], $goods[$k]['type'], $goods[$k]['or_prize'], $goods[$k]['now_prize'], $goods[$k]['expire_time'], $goods[$k]['extend']);
        }
        //矫正,视频，地图通过gid获取优惠券，其他默认第一个gid获取优惠券
        if ($type === 5)
        {
            $gid = 0;
            $cgid = 19;
        } else
        {
            $gid = $gid ?: current($goods)['gid'];
            //获取官方商品活动信息
            $cgid = $goods ? current($goods)['gid'] : 0;
        }
        if ($goods)
        {
            $arr['goods_data'] = $goods = array_values($goods);
        } else
        {
            throw new ApiException('商品不能存在', 200, 0);
        }
        //判断当前商品是否解锁,针对地图
        $is_unlock = false;
        if ($type === 5 && in_array($cgid, $unlock_gids))
        {
            $is_unlock = true;
        }
        //判断当前商品是否解锁,针对本命预测
        if ($type === 7 && in_array($gid, $unlock_gids))
        {
            $is_unlock = true;
        }
        //若当前是生时校正，运势，地图，报告客户端未传入rid，则默认自己的档案，进行查询是否是内部vip
        if (!$rid && in_array($type, [1, 2, 3, 4, 5, 7, 17], true))
        {
            $self_recode = (new Recode())->getSelfRecode(['uid' => $header->user['id']]);
            if ($self_recode)
            {
                $rid = $self_recode['id'];
            }
        }
        //若是内部vip或者是苹果支付或商品已解锁则不显示活动和优惠券信息
        $vipLevel = Util::getVips($header->user['id'], $type, $rid, $gid);
        if ($vipLevel || $is_unlock === true)
        {
            unset($arr['active_data']);
            $arr['coupon_data'] = [
                'usable_num' => 0,
                'name' => '优惠券',
            ];
        } else
        {
            $goods_price = $goods ? $goods[0]['price'] : 0;
            $activing = $activingModel->getActivingGood($type, $gid, $start_time);
            if ($activing)
            {
                $arr['active_data']['name'] = $activing['name'];
                $discount = $arr['active_data']['discount'] = sprintf('%.2f', $activing['attr']);
            }
            //获取活动后的商品价格
            $rec_price = $discount ? $goods_price * $discount : $goods_price;
            //获取用户可用的优惠券
            if ($header->user['id'])
            {
                if ($gid)
                {
                    $coupon = (new UserCoupon())->getUsableList($header->user['id'], [$gid], $rec_price);
                } else
                {
                    $coupon = (new UserCoupon())->getUsableList($header->user['id'], [$cgid], $rec_price);
                }
            }
            $arr['coupon_data'] = [
                'usable_num' => isset($coupon) ? count($coupon) : 0,
                'name' => '优惠券',
            ];
        }
        $arr['avatar'] = $header->user['avatar'];
        $arr['nickname'] = $header->user['nickname'];
        //            $arr['has_mobile'] = $user['tel'] ? 1 : 0;
        $arr['has_mobile'] = 1;// TODO 暂时关闭下单验证手机号逻辑

        $user_coin = (new ZhunleUserAccount())->getUserCoinFromCache($header->user['id']);  // 账户信息
        $arr['coin_num'] = (int)($user_coin['balance'] ?? 0);// 准币余额
        $arr['coin_pwd_status'] = (isset($user_coin['password']) && $user_coin['password']) ? 1 : 0;  // 是否设置了支付密码
        if ($type === 17)
        {
            $arr['notice2'] = $this->getSynastryReportUnlockNotice($header->user['id'], $rid, $rid2, $srid, $relationId, $start_time, $endTime);
        } else
        {
            $arr['notice2'] = $this->getFortuneUnlockInfo($type, $header->user['id'], $rid, $gid, $start_time);
        }

        return $arr;
    }

    ############################################## todo 版本2.7.0开始的新版逻辑 ################################################

    /**
     * 商品结构重组 (获取活动信息及优惠券信息和商品参与活动后的最终支付价格,未去除优惠券折扣)
     * @param $header
     * @param $type
     * @param array $goods 当前商品类型的所有商品信息
     * @param int $rid
     * @param int $rid2
     * @param string $start_time
     * @param array $gids 要解锁的商品ID
     * @param array $param ['isGoodInfo'=>直播间活动名称是否固定]
     * @return array
     * @throws ApiException
     */
    public function resetGoodsInfo2($header, $type, $goods, $rid = 0, $rid2 = 0, $start_time = '', $gids = [], $param = [])
    {
        $host = Env::get('host.domain');
        $oss = Env::get('host.photo');
        $type = (int)$type;
        $gid = (int)current($gids); //解锁的商品ID
        $arr = [];
        $srid = 0;
        $relationId = NULL;
        $endTime = null;
        $rec_price = 0;//当前商品参与活动后的最终支付价格,未去除优惠券折扣

        //若是内部vip或者是苹果支付或商品已解锁则不显示活动和优惠券信息
        $selfRecode = (new Recode())->getSelfRecode(['uid' => $header->user['id']]);
        $selfId = $selfRecode['id'] ?? 0;
        $ridTmp = $rid == $selfId ? $rid : $rid2;
        $param['vip_level'] = $vipLevel = Util::getVips($header->user['id'], $type, $ridTmp, $gid);
        $param['rid'] = $rid;
        $param['rid2'] = $rid2;
        //商品信息根据商品类型进行处理
        switch (true)
        {
            //若是校准生辰，视频获取具体商品信息
            case in_array($type, [6, 16, 22, 28, 35], true)://教学视频,塔罗,合盘报告 只获取一个具体的商品信息
                $goodsData = $this->goodsInfoArr($header, $type, $goods, $gids, [], $param);
                $arr['goods_data'] = [$goodsData['data'][$gid]];
                $arr['rec_price'] = $rec_price = $goodsData['price'];
                break;
            case $type === 17:
                $goodsData = $this->goodsInfoArr($header, $type, $goods, $gids, [], $param);
                $relationId = $goods[$gid]['relation_id'];
                $srid = $goods[$gid]['srid'];
                $arr['fortune_time_range'] = [
                    'start_time' => date('Y-m'),
                    'end_time' => '2058-01',
                ];
                $sTime = strtotime($start_time . '-01');
                $start_time = (int)date('Ym', $sTime);
                $endTime = (int)date('Ym', strtotime($goods[$gid]['expire_time'], $sTime));
                $arr['goods_data'] = $goodsData['data'];
                $arr['rec_price'] = $goodsData['price'];
                break;
            case in_array($type, [5, 7, 23], true)://地图和本命预测商品处理，判断商品是否购买以及幸运之城打包价格处理
                $goods_gids = array_column($goods, 'id');
                $unlcok_goods = OrdersLib::CheckPayGids($header->user['id'], $rid, $type, $goods_gids, $rid2);//当前档案所有已解锁的GID
                $goodsData = $this->goodsInfoArr($header, $type, $goods, $gids, $unlcok_goods['gids'], $param);
                //商品打包价格
                $arr['pack_price'] = $goodsData['data'][87]['price'] ?? null;
                $arr['goods_data'] = $goodsData['data'];
                $arr['rec_price'] = $rec_price = $goodsData['price'];

                if ($type === 5)
                {
                    $goodsGidConfig = config('goods');
                    $goodsDataKey = $goodsGidConfig['acg_pack_id'];
                    $linesGoodsKey = $goodsGidConfig['acg_line_id'];
                    $cityGoodsKey = $goodsGidConfig['acg_city_id'];
                    if (Util::CheckAppVersion('2.9.6') !== '小')
                    {
                        unset($arr['goods_data'][19]);
                        $linesGoodsData = array_intersect_key($arr['goods_data'], array_flip($linesGoodsKey));
                        $cityGoodsData = array_intersect_key($arr['goods_data'], array_flip($cityGoodsKey));
                        $arr['option_goods_data'] = [['title' => '命格线', 'list' => array_values($linesGoodsData)], ['title' => '城市排行', 'list' => array_values($cityGoodsData)]];
                        $arr['goods_data'] = array_intersect_key($arr['goods_data'], array_flip($goodsDataKey));
                    } else
                    {
                        $arr['pack_price'] = $goodsData['data'][19]['price'] ?? null;
                        $arr['goods_data'] = array_intersect_key($arr['goods_data'], array_flip(array_merge($linesGoodsKey, [18, 19])));
                    }
                }
                break;
            default:
                $goodsData = $this->goodsInfoArr($header, $type, $goods, $gids, [], $param);
                $arr['goods_data'] = $goodsData['data'];
                $arr['rec_price'] = $rec_price = $goodsData['price'];
                if ($type === 3)//获取月运购买时间范围
                {
                    $arr['fortune_time_range'] = [
                        'start_time' => config('fortune.fortune_time_range')['month']['start'],
                        'end_time' => config('fortune.fortune_time_range')['month']['end'],
                    ];
                } elseif ($type === 4)//获取年运购买时间范围
                {
                    $arr['fortune_time_range'] = [
                        'start_time' => date('Y'),// 不能购买之前的运势
                        'end_time' => config('fortune.fortune_time_range')['year']['end'],
                    ];
                } elseif ($type === 8)
                {
                    $arr['link_tip'] = [
                        'img' => $oss . '/vip/images/good_link_tip.png',
                        'target' => 'link',
                        'link' => $host . '/web/vip/vip_right?need_auth=0'
                    ];
                    if (Util::CheckAppVersion('2.10.5') !== '小')
                    {
                        $arr['link_tip']['img'] = $oss . '/vip/images/good_link_tip2.png';
                    }
                }
                break;
        }

        //若当前是生时校正，运势，地图，报告客户端未传入rid，则默认自己的档案，进行查询是否是内部vip
        if (!$rid && in_array($type, [1, 2, 3, 4, 5, 7, 17], true))
        {
            $self_recode = (new Recode())->getSelfRecode(['uid' => $header->user['id']]);
            if ($self_recode)
            {
                $rid = $self_recode['id'];
            }
        }

        //获取用户相关信息
        $arr['avatar'] = $header->user['avatar'];
        $arr['nickname'] = $header->user['nickname'];
        //            $arr['has_mobile'] = $user['tel'] ? 1 : 0;
        $arr['has_mobile'] = 1;// TODO 暂时关闭下单验证手机号逻辑
        $arr['is_vip'] = (bool)(new ZlUserVip())->getUserVipLevel($header->user['id']);//是否是vip

        $arr['img_info'] = [
            'url' => '/test/order/goods_tip_img.png',
            'target' => 'local',
            'link' => 'pay_order?type=8&need_auth=2'
        ];
        $arr['coupon_data'] = [
            'data' => [],
            'usable_num' => 0,
            'name' => '优惠券',
        ];
        $unlockStatus = (isset($goodsData['data'][$gid]['is_unlock']) && $goodsData['data'][$gid]['is_unlock']) ? 1 : 0;
        //获取用户可用的优惠券
        if ($header->user['id'])
        {
            //不是内部vip且商品未解锁,展示优惠券信息
            if (!$vipLevel && !$unlockStatus)
            {
                $coupon = (new UserCoupon())->getUsableList($header->user['id'], $gids, $rec_price);
                $arr['coupon_data'] = [
                    'data' => $coupon,
                    'usable_num' => count($coupon),
                    'name' => '优惠券',
                ];
            }
            $user_coin = (new ZhunleUserAccount())->getUserCoinFromCache($header->user['id']);  // 账户信息
            $arr['coin_num'] = (int)($user_coin['balance'] ?? 0);// 准币余额
            $arr['coin_pwd_status'] = (isset($user_coin['password']) && $user_coin['password']) ? 1 : 0;  // 是否设置了支付密码
            if ($type === 17)
            {
                $arr['notice2'] = $this->getSynastryReportUnlockNotice($header->user['id'], $rid, $rid2, $srid, $relationId, $start_time, $endTime);
            } else
            {
                $arr['notice2'] = $this->getFortuneUnlockInfo($type, $header->user['id'], $rid, $gid, $start_time);
            }
        }
        return $arr;
    }

    /**
     * 商品数据结构 (商品参与活动后的最终支付价格,未去除优惠券折扣)
     * @param $header
     * @param $type
     * @param $goods
     * @param array $gids 获取指定商品折后总价 (type=>8时,必传)
     * @param array $unlock_gids 解锁的所有商品id
     * @param array $param ['isGoodInfo'=>直播间活动名称是否固定]
     * @return array
     * @throws \Exception
     */
    public function goodsInfoArr($header, $type, $goods, $gids = [], $unlock_gids = [], $param = [])
    {
        $arr = [
            'data' => [],
            'price' => 0,//所有商品优惠后的总价格
        ];
        $type = (int)$type;
        if (current($gids) && !in_array($type, [14, 30], true))
        {
            $intersectGids = array_intersect($gids, array_column($goods, 'id'));
            if (!$intersectGids)
            {
                throw new ApiException('未知的商品');
            }
        }
        $recode = isset($param['rid']) ? (new \app\common\cachemodel\Recode())->getInfoById($param['rid']) : [];
        $price = 0;
        $appleGoods = config('apple_pay_goods');
        $starTimeInt = !empty($param['start_time']) ? strtotime($param['start_time']) : 0;
        foreach ($goods as $good)
        {
            $tmpGid = (int)$good['id'];
            $tmp = $this->resetGoodsInfoArr($header, $type, $good, $gids, $unlock_gids, $param);
            $paramTmp = $param;
            $paramTmp['order_type'] = $type;
            $paramTmp['trade_type'] = 1;
            $paramTmp['gids'] = [$good['id']];
            $paramTmp['start_time'] = $starTimeInt;
            $vipPrice = OrdersLib::innerVipGoodPrice($header->user['id'], $param['vip_level'], $paramTmp);
            if ($vipPrice !== false)
            {
                $price = $vipPrice;
                $tmp['price'] = $vipPrice;
                $tmp['active_data'] = null;
            } elseif (in_array($tmpGid, $gids, false))
            {
                if ($tmp['active_data'])
                {
                    $price += round($tmp['active_data']['now_price'], 2);
                } else
                {
                    $price = round($tmp['price'], 2);
                }
            }
            switch ($type)
            {
                case 3:
                    $tmp['apple_goods'] = $appleGoods['fortune_month'][$tmpGid] ?? [];
                    break;
                case 4:
                    $tmp['apple_goods'] = $appleGoods['fortune_year'][$tmpGid] ?? [];
                    break;
                case 7:
                    $tmp['apple_goods'] = $appleGoods['natal_report'][$tmpGid] ?? [];
                    break;
                case 8:
                    switch ($tmpGid)
                    {
                        case 20112:
                            $vipOrder = (new Orders())->where(['uid' => $header->user['id'], 'order_type' => 8, 'gid' => 20112, 'status' => 4])->count('id');
                            if (!$vipOrder)
                            {
                                $tmp['price'] = '19.90';
                                $tmp['tag_des'] = '限首月5折';
                                $price = round($tmp['price'], 2);
                            } else
                            {
                                $tmp['tag_des'] = '特惠8折';
                            }
                            break;
                        case 154:
                            $tmp['tag_des'] = '特惠8折';
                            break;
                        case 155:
                            $tmp['tag_des'] = '特惠7折';
                            break;
                        case 156:
                            $tmp['tag_des'] = '特惠6折';
                            break;
                        case 20111:
                        case 157:
                            $tmp['tag_des'] = '特惠5折';
                            break;
                    }
                    break;
                case 27:
                    if ($tmpGid === 91)
                    {
                        $startTimeTmp = date('Y', strtotime($param['start_time']));
                        //获取人生阶段
                        $stateYear = Util::getRecodeStageyear($recode, (int)$startTimeTmp);
                        $tmp['des'] = "人生第{$stateYear['num_han']}阶段 ({$stateYear['start_year']}-{$stateYear['end_year']})";
                    }
                    break;
                case 28:
                    if (Util::IsHuawei())
                    {
                        if ($tmpGid === 106)
                        {
                            $tmp['name'] = '取用详解';
                        } elseif ($tmpGid === 107)
                        {
                            $tmp['name'] = '格局解读';
                        }
                    }
                    break;
                case 30://AI解答(骰子塔罗)
                    switch ($tmpGid)
                    {
                        case 145:
                        case 146:
                        case 147:
                            $tmp['tag_des'] = '特惠5折';
                            break;
                        case 151:
                            $tmp['tag_des'] = '特惠9折';
                            break;
                        case 152:
                            $tmp['tag_des'] = '特惠8折';
                            break;
                        case 153:
                            $tmp['tag_des'] = '特惠7折';
                            break;
                    }
                    break;
                case 31:
                    switch ($tmpGid)
                    {
                        case 148:
                            $tmp['tag_des'] = '特惠7折';
                            break;
                        case 149:
                            $tmp['tag_des'] = '特惠6折';
                            break;
                        case 150:
                            $tmp['tag_des'] = '特惠5折';
                            break;
                    }
                    break;
            }
            $arr['data'][$tmpGid] = $tmp;
        }
        $arr['price'] = sprintf('%.2f', $price);
        return $arr;
    }

    /**
     * (活动折扣信息组合)
     * @param $header
     * @param $type
     * @param $good
     * @param array $gids 获取指定商品折后总价 (type=>8时,必传)
     * @param array $unlockGids 已解锁的商品id
     * @param array $param ['isGoodInfo'=>直播间活动名称是否固定]
     * @return array
     * @throws \Exception
     */
    public function resetGoodsInfoArr($header, $type, $good, $gids = [], $unlockGids = [], $param = [])
    {
        $questionGoodsType = '';
        $good['id'] = (int)$good['id'];
        if ($type === 14)
        {
            $good['now_prize'] = $good['now_price'];
        } elseif ($type === 22)
        {
            $res = (new Zlcr2UserQuestion())->getQuestionType($good['id']);
            //蹭看处理
            if ($res['type'] === 1)
            {
                $good['name'] = '问答/蹭看';
            } else
            {
                //追问处理
                if ($res['type'] === 2)
                {
                    $questionGoodsType = '（追问）';
                }
                switch ($res['sec'])
                {
                    case 1:
                        $good['name'] = '问答/星盘' . $questionGoodsType;
                        break;
                    case 2:
                        $good['name'] = '问答/骰子' . $questionGoodsType;
                        break;
                    case 3:
                        $good['name'] = '问答/塔罗' . $questionGoodsType;
                        break;
                }
            }
        }
        $extend = isset($good['extend']) ? json_decode($good['extend'], true) : [];
        if (Util::CheckAppVersion('2.9.7') === '大' && Util::IsIos())
        {
            $goodsDes = $extend['ios_goods_des'] ?? '';
        } else
        {
            $goodsDes = $extend['goods_des'] ?? '';
        }
        if (in_array($good['id'], [20106, 20112], true))
        {
            $tips = '连续包月到期自动续费1个月，可随时取消';
        } elseif (in_array($good['id'], [20105, 20111], true))
        {
            $tips = '连续包年到期自动续费1年，可随时取消';
        }
        $tmp = [
            'gid' => $good['id'],
            'name' => $good['name'],
            'expire_time' => $good['expire_time'] ?? '',
            'img' => self::goodsImg($type),
            'des' => $goodsDes,
            'des2' => '',
            'tips' => $tips ?? '',
            'price' => sprintf('%.2f', $good['now_prize']),//商品真实现价
            'or_price' => isset($good['or_prize']) ? sprintf('%.2f', $good['or_prize']) : '',//商品真实现价
            'active_data' => null,
            'tag_des' => ''
        ];
        $isCombination = false;//是否是组合价
        $goodsGidConfig = config('goods');
        //幸运之城打包组合价格处理
        if ($type === 5 && $good['id'] === 105)
        {
            $diff = array_intersect([18, 102, 103, 104], $unlockGids);//判断已经解锁的打包商品id
            sort($diff);
            $priceCombination = [
                //命格线[103]+城市排行[104]+具体影响[102]
                '18' => '144.00',
                //命格线[103]+城市排行[104]+命运之城[18]
                '102' => '168.00',
                //城市排行[104]+具体影响[102]+命运之城[18]
                '103' => '96.00',
                //命格线[103]+命运之城[18]+具体影响[102]
                '104' => '120.00',
                //城市排行[104]+命格线[103]
                '18-102' => '144.50',
                //城市排行[104]+具体影响[102]
                '18-103' => '79.00',
                //命格线[103]+具体影响[102]
                '18-104' => '109.00',
                //城市排行[104]+命运之城[18]
                '102-103' => '93.50',
                //命格线[103]+命运之城[18]
                '102-104' => '119.00',
                //具体影响[102]+命运之城[18]
                '103-104' => '49.00',
            ];
            //若购买了两种以上的打包商品则价格为剩下的打包商品的价格
            if (count($diff) === 3)
            {
                $isCombination = true;
                $unlockGidTmp = array_diff([18, 102, 103, 104], $diff);//未购买的商品id
                $packGoodsInfo = $this->batchGetInfoByIds($goodsGidConfig['acg_pack_id']);
                $tmp['price'] = $packGoodsInfo[current($unlockGidTmp)]['now_prize'];
            } else if (isset($priceCombination[implode('-', $diff)]))
            {
                $isCombination = true;
                $tmp['price'] = $priceCombination[implode('-', $diff)];
            }
            $tmp['tag_des'] = $tmp['price'] . '元打包解锁';
        }
        //若直播间有活动默认显示直播间活动,但若官方活动折扣力度大于直播播间,则显示官方活动
        $activeData = null;
        if (!empty($good['active']))
        {
            $discountedPrice = $isCombination ? $tmp['price'] * (1 - $good['active']['attr']) : $tmp['price'] - $good['active']['price'];
            $nowPrice = $isCombination ? $tmp['price'] * $good['active']['attr'] : $good['active']['price'];
            $tmp['active_data'] = $activeData = [
                'type' => 1,
                'discount_type' => $good['active']['type'],
                'attr' => $good['active']['attr'],
                'id' => $good['active']['id'],
                'des' => $good['active']['des'],
                'name' => $good['active']['name'],
                'discount_price' => sprintf('%.2f', $discountedPrice),//折扣优惠价格
                'now_price' => sprintf('%.2f', $nowPrice),//优惠后的现价
                'count_down' => $good['active']['count_down']//活动倒计时
            ];
        }
        if (!empty($good['live_active']))
        {
            $liveDiscountedPrice = $isCombination ? $tmp['price'] * (1 - $good['live_active']['attr']) : $tmp['price'] - $good['live_active']['price'];
            $liveNowPrice = $isCombination ? $tmp['price'] * $good['live_active']['attr'] : $good['live_active']['price'];
            //商品信息直播间活动名称固定
            if (isset($param['isGoodInfo']) && $param['isGoodInfo'])
            {
                $name = '直播间活动';
            } else
            {
                $name = $good['live_active']['name'];
            }
            $tmp['active_data'] = [
                'type' => 2,
                'discount_type' => $good['live_active']['type'],
                'attr' => $good['live_active']['attr'],
                'id' => $good['live_active']['id'],
                'des' => $good['live_active']['des'],
                'name' => $name,
                'discount_price' => sprintf('%.2f', $liveDiscountedPrice),
                'now_price' => sprintf('%.2f', $liveNowPrice),
                'count_down' => 0
            ];
            if (!empty($good['active']) && $good['live_active']['price'] > $good['active']['price'])
            {
                $tmp['active_data'] = $activeData;
            }
        }

        //todo 因为苹果新版本统一用准币支付,精度处理
        //  因准币支付时,日运价格两端不统一,暂时关闭
//        if (Util::IsIos() && Util::CheckAppVersion('2.9.8') !== '小')
//        {
//            $tmp['price'] = sprintf('%.2f', ceil($tmp['price'] * (10 ** 1)) / (10 ** 1));
//            if (!empty($tmp['active_data']))
//            {
//                $tmp['active_data']['discount_price'] = ceil($tmp['active_data']['discount_price'] * (10 ** 1)) / (10 ** 1);
//                $tmp['active_data']['now_price'] = floor($tmp['active_data']['now_price'] * (10 ** 1)) / (10 ** 1);
//            }
//        }

        $unlocakStatus = 0;
        if (in_array($good['id'], $unlockGids, false))
        {
            $unlocakStatus = 1;
        } elseif ($type === 5)//判断地图当前商品是否已解锁
        {
            $goodsDataKey = $goodsGidConfig['acg_id'];
            $linesGoodsKey = array_diff($goodsGidConfig['acg_line_id'], [14, 15]);
            $cityGoodsKey = $goodsGidConfig['acg_city_id'];
            if (in_array(19, $unlockGids, false) && in_array($good['id'], array_merge($linesGoodsKey, $cityGoodsKey, [18, 103, 104]), false))//旧版打包解锁
            {
                $unlocakStatus = 1;
            } elseif (in_array(103, $unlockGids, false) && in_array($good['id'], $linesGoodsKey, false))//命格线打包解锁
            {
                $unlocakStatus = 1;
            } elseif (in_array(104, $unlockGids, false) && in_array($good['id'], $cityGoodsKey, false))//城市排行打包解锁
            {
                $unlocakStatus = 1;
            } else if (in_array(105, $unlockGids, false) && in_array($good['id'], $goodsDataKey, false))//全内容打包解锁
            {
                $unlocakStatus = 1;
            } elseif (in_array($good['id'], [14, 15], false))//默认解锁的命格线
            {
                $unlocakStatus = 1;
            }
        }
        $tmp['is_unlock'] = $unlocakStatus;
        //若当前是vip，则获取vip有效时间
        if ($type === 8)
        {
            //获取用户当前vip有效时间
            $UserVip = OrdersLib::getUserVipTime($header->user['id'], $good['id']);
            $tmp['vip_expired_des'] = '会员有效期至' . date('Y-m-d', $UserVip['vip_end_time']);
        }
        return $tmp;
    }

    /**
     * 获取商品跳转地址
     * @param $goodsType
     * @param $link
     * @param int $rid
     * @param int $unlock_status 解锁状态 0=>未解锁
     */
    public function goodsTargetLink($goodsType, &$link, $rid = 0, $unlock_status = 0)
    {
        //未包含时间字段需自动处理
        if (strpos($link, 'time') === false)
        {
            $now_date = date('Y-m-d');
            [$now_year, $now_month, $now_day] = explode('-', $now_date);
            if ($goodsType === 3)
            {
                //用户在本月25号至月底 点击解锁月运， 直接跳转至下月月运详情
                if ($now_day > 24)
                {
                    if ((int)$now_month === 12)
                    {
                        // 若未解锁当前运势，则跳转至下一年
                        if ($unlock_status === 0)
                        {
                            ++$now_year;
                            $now_month = 1;
                        }
                    } else
                    {
                        // 若未解锁当前运势，则跳转至下月
                        if ($unlock_status === 0)
                        {
                            ++$now_month;
                        }
                    }
                }
                $time = $now_year . '-' . $now_month;
                if ($rid)
                {
                    $link = "fortune_for_month?rid={$rid}&time={$time}&need_auth=1";
                } else
                {
                    $link = "fortune_for_month?time={$time}&need_auth=1";
                }
            } elseif ($goodsType === 4)
            {
                $monthDay = $now_month . $now_day;
                if (($monthDay >= 1025 && $unlock_status === 0) || ($monthDay >= 1210 && $unlock_status === 1))
                {
                    ++$now_year;
                }
                if ($rid)
                {
                    $link = "fortune_for_year?rid={$rid}&time={$now_year}&need_auth=1";
                } else
                {
                    $link = "fortune_for_year?time={$now_year}&need_auth=1";
                }
            }
        }
    }
}
